//
//  DetailViewController.m
//  视频练习
//
//  Created by dllo on 15/9/30.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "DetailViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "AsynURLConnection.h"
#import "ContentViewCell.h"
#import "ContentModel.h"

@interface DetailViewController ()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,retain)AVPlayer *player;//播放器对象
@property (retain, nonatomic)UIView *container; //播放器容器
@property(nonatomic,retain)UIButton *playOrPause;//播放/暂停按钮
@property (retain, nonatomic)UIProgressView *progress;//播放进度
@property(nonatomic,retain)UILabel *currentTime;
@property(nonatomic,retain)UILabel *allTime;
@property(nonatomic,retain)UISlider *slider;
@property(nonatomic,retain)UITableView *table;
@property(nonatomic,retain)NSMutableArray *tabArr;
@end

@implementation DetailViewController
- (void)dealloc
{
    [self.progress release];
    [_playOrPause release];
    [_currentTime release];
    [_allTime release];
    [_slider release];
    [_tabArr release];
    [_table release];
    [self removeObserverFromPlayerItem:self.player.currentItem];
    [self removeNotification];
    [super dealloc];

}
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.tabArr = [NSMutableArray array];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupUI];
    [self.player play];
    [self createTavleview];
    [self praser];
    self.view.backgroundColor = [UIColor whiteColor];

}
#pragma mark - 私有方法
-(void)setupUI{
    //创建播放器层
    self.container = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height/3)];
        [self.view addSubview:self.container];
    AVPlayerLayer *playerLayer=[AVPlayerLayer playerLayerWithPlayer:self.player];
    
    playerLayer.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height/3);
//    playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;//视频填充模式
#pragma mark - 视频的填充满模式
    playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    [self.container.layer addSublayer:playerLayer];
    
    self.playOrPause = [[UIButton alloc]initWithFrame:CGRectMake(10*OffWidth, [UIScreen mainScreen].bounds.size.height/3, 30*OffWidth, 30*OffHeight)];
    [self.view addSubview:self.playOrPause];
    
    [self.playOrPause setImage:[UIImage imageNamed:@"zanting.png"] forState:UIControlStateNormal];
    [self.playOrPause addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    self.slider = [[UISlider alloc]initWithFrame:CGRectMake(100*OffWidth, [UIScreen mainScreen].bounds.size.height/3, 200*OffWidth, 30*OffHeight)];
    [self.view addSubview:self.slider];
    [self.slider addTarget:self action:@selector(addProgressObserver) forControlEvents:UIControlEventValueChanged];
    [self.slider release];
    
#pragma mark - 创建播放时间
    self.currentTime = [[UILabel alloc]initWithFrame:CGRectMake(50*OffWidth, [UIScreen mainScreen].bounds.size.height/3, 50, 30*OffHeight)];
    [self.view addSubview:self.currentTime];
    [self.currentTime release];
    self.allTime = [[UILabel alloc]initWithFrame:CGRectMake(310*OffWidth, [UIScreen mainScreen].bounds.size.height/3, 50, 30*OffHeight)];
    [self.view addSubview:self.allTime];
    [self.allTime release];
    self.allTime.text = [NSString stringWithFormat:@"%d%d:%d%d",0,0,0,0];
    self.currentTime.text = [NSString stringWithFormat:@"%d%d:%d%d",0,0,0,0];

    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30*OffWidth, 30*OffHeight)];
  
    [button setImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];

    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button];
    [button release];
}
-(void)click:(UIButton *)button
{
    [self.player pause];
    [self.navigationController popViewControllerAnimated:YES];
}
/**
 *  截取指定时间的视频缩略图
 *
 *  @param timeBySecond 时间点
 */

/**
 *  初始化播放器
 *
 *  @return 播放器对象
 */
-(AVPlayer *)player{
    if (!_player) {
        AVPlayerItem *playerItem=[self getPlayItem:0];
        _player=[AVPlayer playerWithPlayerItem:playerItem];
        [self addProgressObserver];
        [self addObserverToPlayerItem:playerItem];
    }
    return _player;
}

/**
 *  根据视频索引取得AVPlayerItem对象
 *
 *  @param videoIndex 视频顺序索引
 *
 *  @return AVPlayerItem对象
 */
-(AVPlayerItem *)getPlayItem:(int)videoIndex{
    NSString *urlStr=[NSString stringWithFormat:self.url,videoIndex];
    urlStr =[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url=[NSURL URLWithString:urlStr];
    AVPlayerItem *playerItem=[AVPlayerItem playerItemWithURL:url];
    return playerItem;
}
#pragma mark - 通知
/**
 *  添加播放器通知
 */
-(void)addNotification{
    //给AVPlayerItem添加播放完成通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];
}

-(void)removeNotification{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

/**
 *  播放完成通知
 *
 *  @param notification 通知对象
 */
-(void)playbackFinished:(NSNotification *)notification{
    NSLog(@"视频播放完成.");
}
#pragma mark - 监控
/**
 *  给播放器添加进度更新
 */
-(void)addProgressObserver{
    AVPlayerItem *playerItem = self.player.currentItem;
//    UIProgressView *progress = self.progress;
    //这里设置每秒执行一次
    [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        float current=CMTimeGetSeconds(time);
        float total=CMTimeGetSeconds([playerItem duration]);
        NSLog(@"当前已经播放%.2fs.",current);
        
#pragma mark - 判断时间
        
        
        
        int minCount = current / 60;
        double s = current - 60 * minCount;
        NSLog(@"s = %f",s);
        if (current < 60) {
            // current/60.00
            
            if (current < 10) {
                self.currentTime.text = [NSString stringWithFormat:@"00:0%.0f",current];
            }
            else
            {
              self.currentTime.text = [NSString stringWithFormat:@"00:%.0f",current];
            }
        }
        
        if (current < 3600.00 && current > 60)
        {
            if (minCount < 10) {
                if (s<10) {
                    self.currentTime.text = [NSString stringWithFormat:@"0%d:0%.0f",minCount,s];
                }
                else
                {
                  self.currentTime.text = [NSString stringWithFormat:@"0%d:%.0f",minCount,s];
                }
            }
            else
            {
                if (s < 10) {
                     self.currentTime.text = [NSString stringWithFormat:@"%.0f:0%.0f",current,s];
                }
                else
                {
                self.currentTime.text = [NSString stringWithFormat:@"%.0f:%.0f",current,s];
                }
            }
            
        }
        if (current) {
            [self.slider setValue:(current/total) animated:YES];
        }
    }];
}

/**
 *  给AVPlayerItem添加监控
 *
 *  @param playerItem AVPlayerItem对象
 */
-(void)addObserverToPlayerItem:(AVPlayerItem *)playerItem{
    //监控状态属性，注意AVPlayer也有一个status属性，通过监控它的status也可以获得播放状态
    [playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    //监控网络加载情况属性
    [playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
}
-(void)removeObserverFromPlayerItem:(AVPlayerItem *)playerItem{
    [playerItem removeObserver:self forKeyPath:@"status"];
    [playerItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
}
/**
 *  通过KVO监控播放器状态
 *
 *  @param keyPath 监控属性
 *  @param object  监视器
 *  @param change  状态改变
 *  @param context 上下文
 */
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    AVPlayerItem *playerItem=object;
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerStatus status= [[change objectForKey:@"new"] intValue];
        
        if(status==AVPlayerStatusReadyToPlay){
            NSLog(@"正在播放...，视频总长度:%.2f",CMTimeGetSeconds(playerItem.duration));
           double current = CMTimeGetSeconds(playerItem.duration);
            int minCount = current / 60;
            double s = current - 60 * minCount;
            
            if (current < 60) {
                // current/60.00
                
                if (current < 10) {
                    self.allTime.text = [NSString stringWithFormat:@"00:0%.0f",current];
                }
                else
                {
                    self.allTime.text = [NSString stringWithFormat:@"00:%.0f",current];
                }
            }
            
            if (current < 3600.00 && current > 60)
            {
                if (minCount < 10) {
                    if (s<10) {
                        self.allTime.text = [NSString stringWithFormat:@"0%d:0%.0f",minCount,s];
                    }
                    else
                    {
                        self.allTime.text = [NSString stringWithFormat:@"0%d:%.0f",minCount,s];
                    }
                }
                else
                {
                    if (s < 10) {
                        self.allTime.text = [NSString stringWithFormat:@"%.0f:0%.0f",current,s];
                    }
                    else
                    {
                        
                        self.allTime.text = [NSString stringWithFormat:@"%.0f:%.0f",current,s];
                    }
                }
                
            }
            
                   }
    }else if([keyPath isEqualToString:@"loadedTimeRanges"]){
        NSArray *array=playerItem.loadedTimeRanges;
        CMTimeRange timeRange = [array.firstObject CMTimeRangeValue];//本次缓冲时间范围
        float startSeconds = CMTimeGetSeconds(timeRange.start);
        float durationSeconds = CMTimeGetSeconds(timeRange.duration);
        NSTimeInterval totalBuffer = startSeconds + durationSeconds;//缓冲总长度
        NSLog(@"共缓冲：%.2f",totalBuffer);
        //
    }
}
-(void)buttonAction:(UIButton *)sender
{

//    AVPlayerItemDidPlayToEndTimeNotification
    //AVPlayerItem *playerItem= self.player.currentItem;
    if(self.player.rate == 0){ //说明时暂停
        [sender setImage:[UIImage imageNamed:@"zanting.png"] forState:UIControlStateNormal];
        [self.player play];
    }else if(self.player.rate == 1){//正在播放
        [self.player pause];
        [sender setImage:[UIImage imageNamed:@"bofang.png"] forState:UIControlStateNormal];
    }
}

/**
 *  切换选集，这里使用按钮的tag代表视频名称
 *
 *  @param sender 点击按钮对象
 */
- (IBAction)navigationButtonClick:(UIButton *)sender {
    [self removeNotification];
    [self removeObserverFromPlayerItem:self.player.currentItem];
    AVPlayerItem *playerItem=[self getPlayItem:sender.tag];
    [self addObserverToPlayerItem:playerItem];
    //切换视频
    [self.player replaceCurrentItemWithPlayerItem:playerItem];
    [self addNotification];
}
#pragma mark - 评论解析
-(void)praser
{
 //http://api.budejie.com/api/api_open.php?a=dataList&appname=baisishequ&asid=1DDDF06B-87A4-4AE7-B7CF-8819C61B0EB1&c=comment&client=iphone&data_id=15810774&device=iPhone%205&hot=1&jbk=1&mac=&market=&openudid=72244dd2b62c5bc75b9c5ff90be56501274eaafb&page=1&per=50&udid=&ver=3.6.1
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:@"dataList" forKey:@"a"];
     [dic setValue:@"baisishequ" forKey:@"appname"];
     [dic setValue:@"1DDDF06B-87A4-4AE7-B7CF-8819C61B0EB1" forKey:@"asid"];
     [dic setValue:@"comment" forKey:@"c"];
     [dic setValue:@"iphone" forKey:@"client"];
     [dic setValue:self.ids forKey:@"data_id"];
     [dic setValue:@"iPhone%205" forKey:@"device"];
     [dic setValue:@"1" forKey:@"hot"];
     [dic setValue:@"1" forKey:@"jbk"];
     [dic setValue:@"" forKey:@"mac"];
     [dic setValue:@"" forKey:@"market"];
    [dic setValue:@"72244dd2b62c5bc75b9c5ff90be56501274eaafb" forKey:@"openudid"];
    [dic setValue:@"1" forKey:@"page"];
     [dic setValue:@"50" forKey:@"per"];
    [dic setValue:@"" forKey:@"udid"];
    [dic setValue:@"3.6.1" forKey:@"ver"];
    [AsynURLConnection asynWithURL:@"http://api.budejie.com/api/api_open.php" parmaters:dic block:^(NSData *data) {
        NSDictionary *root = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *arr = [root objectForKey:@"data"];
        for (int i = 0; i < arr.count; i++) {
            ContentModel *model = [[ContentModel alloc]init];
            [model setValuesForKeysWithDictionary:arr[i]];
            [self.tabArr addObject:model];
            [model release];
        }
        [self.table reloadData];
    }];
}
#pragma mark - 创建tableview
-(void)createTavleview
{
    self.table = [[UITableView alloc]initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height/3 + 30*OffHeight, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    [self.view addSubview:self.table];
    self.table.delegate = self;
    self.table.dataSource = self;
    self.table.rowHeight = 100*OffHeight;
    [self.table release];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.tabArr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ta = @"22";
    ContentViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ta];
    if (!cell) {
        cell = [[[ContentViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ta]autorelease];
    }
    ContentModel *model = [self.tabArr objectAtIndex:indexPath.row];
    [cell sendModel:model];
    cell.selectionStyle = UITableViewCellAccessoryNone;
    return cell;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
